<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类目名称" prop="cateName">
        <el-input v-model="queryParams.cateName" placeholder="请输入类目名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['admin:spucate:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['admin:spucate:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['admin:spucate:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['admin:spucate:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spucateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="类目名称" align="center" prop="cateName" />
      <el-table-column label="类目icon地址" align="center" prop="cateUrl" >
        <template slot-scope="scope">
          <el-image style="width: 255px;height: 68px"  :src="scope.row.cateUrl" fit="contain"  :preview-src-list="[scope.row.cateUrl]" ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="上级类目" align="center" prop="parentId" :formatter="parentSpuCateFormatter" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['admin:spucate:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['admin:spucate:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品类目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类目名称" prop="cateName">
          <el-input v-model="form.cateName" placeholder="请输入类目名称" />
        </el-form-item>
        <el-form-item label="类目icon图标" prop="cateUrl">
          <el-upload class="avatar-uploader" :action="fileUrl" :show-file-list="false" :on-success="successFile" :before-upload="beforeAvatarUpload">
            <img v-if="form.cateUrl" :src="form.cateUrl" class="avatar" style="width:200px;height:200px;">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="上级类目" prop="parentId">
          <el-select
            v-model="form.parentId"
            placeholder="上级类目"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in spuCateOptions"
              :key="dict.id"
              :label="dict.cateName"
              :value="dict.id"
              :disabled="dict.parentId != '-1'"
            >
            <div v-if="dict.id == '-1'" >
              <span style="float: left; color: #8492a6; font-size: 13px;">{{ dict.cateName }}</span>
            </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSpucate, getSpucate, delSpucate, addSpucate, updateSpucate, exportSpucate } from "@/api/admin/spucate";
import { fileUrl } from "@/constant/constant"

export default {
  name: "Spucate",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileUrl: "",
      spuCateOptions:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品类目表格数据
      spucateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cateName: null,

        cateUrl: null,

        parentId: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cateName: [
          { required: true, message: "类目名称不能为空", trigger: "blur" }
        ],

        parentId: [
          { required: true, message: "上级类目 -1代表顶级不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getList();
    this.fileUrl  = fileUrl
  },
  methods: {
    /** 查询商品类目列表 */
    getList() {
      this.loading = true;
      listSpucate(this.queryParams).then(response => {
        this.spucateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      // 缓冲所有
      listSpucate({pageNum: 1,pageSize: 10000}).then(response =>{
        this.spuCateOptions = response.rows;
        this.spuCateOptions.unshift({id:'-1',cateName:'顶级分类',parentId:'-1'})
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,

        cateName: null,

        cateUrl: null,

        parentId: null,

        createBy: null,

        createTime: null,

        updateBy: null,

        updateTime: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    parentSpuCateFormatter(row,column){
      var cateName = "顶级分类"
      this.spuCateOptions.forEach(item =>{
        if (item.id == row.parentId)
          cateName =  item.cateName
      })
      return cateName;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品类目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSpucate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品类目";
      });
    },
    successFile(res, file) {
      this.form.cateUrl = URL.createObjectURL(file.raw);
      this.form.cateUrl = res.data;
    },

    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSpucate(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpucate(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品类目编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSpucate(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品类目数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportSpucate(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 122px;
  height: 122px;
  line-height: 122px;
  text-align: center;
}

.avatar {
  width: 122px;
  height: 122px;
  display: block;
}
</style>
